package com.oumiao.echarts.config;


import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SocketSessionManager {

    /**
     * 保存连接 session 的地方
     */
    private static final Map<Object, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     * @param key
     */
    public static void add(Object key, WebSocketSession session) {
        // 添加 session
        SESSION_POOL.put(key, session);
    }

    /**
     * 删除 session,会返回删除的 session
     * @param token
     * @return
     */
    public static WebSocketSession remove(Object token) {
        // 删除 session
        return SESSION_POOL.remove(token);
    }

    /**
     * 获得 session
     * @param token
     * @return
     */
    public static WebSocketSession get(Object token) {
        return SESSION_POOL.get(token);
    }


    public static void sendToUser(WebSocketSession session,TextMessage json){
        try {
            sendMessage(session,json);
        }catch (Exception e){
            if(session != null){
                try {
                    session.close();
                }catch (Exception ex){

                }
            }
        }
    }

    public static void sendToUser(Object token,TextMessage json) {
        WebSocketSession webSocketSession = get(token);
        sendToUser(webSocketSession, json);
    }

    public static void sendToUser(String token,TextMessage json) {
        WebSocketSession webSocketSession = get(token);
        sendToUser(webSocketSession, json);
    }

    public static void sendToAll(TextMessage json){
        Set<Object> set =  SESSION_POOL.keySet();
        Iterator<Object> iterator = set.iterator();
        while (iterator.hasNext()){
            Object key = iterator.next();
            sendToUser(key,json);
        }
    }

    private static void sendMessage(WebSocketSession webSocketSession, TextMessage json) throws IOException {
//        synchronized (webSocketSession) {

                if(ObjectUtil.isEmpty(webSocketSession)){
                    return;
                }
//                if(!webSocketSession.isOpen()){
//                    return;
//                }
                webSocketSession.sendMessage(json);

//        }
    }

}
